package com.hzh.cusviewdemo.Util;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.Bitmap;
import android.graphics.Paint;
import android.graphics.Point;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.Build;
import android.provider.MediaStore;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Display;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;

import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;

import java.io.IOException;
import java.io.OutputStream;
import java.lang.reflect.Field;
import java.lang.reflect.Method;

public class DisplayUtils {

    static final String TAG = DisplayUtils.class.getSimpleName();

    public static Point getDisplaySize(Activity activity) {
        Point point = new Point();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2) {
            Display display = activity.getWindowManager().getDefaultDisplay();
            display.getSize(point);
        } else {
            Display display = activity.getWindowManager().getDefaultDisplay();
            point.x = display.getWidth();
            point.y = display.getHeight();
        }
        return point;
    }

    /**
     * 根据手机的分辨率从 dp 的单位 转成为 px(像素)
     */
    public static int dip2px(final Activity activity, final float dpValue) {
        final DisplayMetrics metrics = new DisplayMetrics();
        activity.getWindowManager().getDefaultDisplay().getMetrics(metrics);
        final float scale = metrics.density;
        return (int) ((dpValue * scale) + 0.5f);
    }

    /**
     * 根据手机的分辨率从 dp 的单位 转成为 px(像素)
     */
    public static int dp2px(Context context, float dp) {
        float scale = context.getResources().getDisplayMetrics().density;
        return (int) ((dp * scale) + 0.5f);
    }

    /**
     * 根据手机的分辨率从 dp 的单位 转成为 px(像素)
     */
    public static int dip2px(final Context context, final float dpValue) {
        final DisplayMetrics metrics = context.getResources().getDisplayMetrics();
        final float scale = metrics.density;
        return (int) ((dpValue * scale) + 0.5f);
    }

    /**
     * 根据手机的分辨率从 dp 的单位 转成为 px(像素)
     */
//    public static int dip2px(final float dpValue) {
//        return dip2px(GlobalData.app(), dpValue);
//    }

    /**
     * 根据手机的分辨率从 px(像素) 的单位 转成为 dp
     */
    public static int px2dip(final Activity activity, final float pxValue) {
        final DisplayMetrics metrics = new DisplayMetrics();
        activity.getWindowManager().getDefaultDisplay().getMetrics(metrics);
        final float scale = metrics.density;
        return (int) ((pxValue / scale) + 0.5f);
    }

    /**
     * 根据手机的分辨率从 px(像素) 的单位 转成为 dp
     */
    public static int px2dip(final Context context, final float pxValue) {
        final DisplayMetrics metrics = context.getResources().getDisplayMetrics();
        final float scale = metrics.density;
        return (int) ((pxValue / scale) + 0.5f);
    }

    /**
     * 根据手机的分辨率从 px(像素) 的单位 转成为 dp
     */
//    public static int px2dip(final float pxValue) {
//        return px2dip(GlobalData.app(), pxValue);
//    }
    public static void overridingPendingAnim(Activity activity, int inAnim, int outAnim) {
        if (activity == null) {
            return;
        }
        Log.d(TAG, "OverridePending:Activity=" + activity);
        activity.overridePendingTransition(inAnim, outAnim);
    }

    /**
     * 获取一个 View 的缓存视图
     * (前提是这个View已经渲染完成显示在页面上)
     *
     * @param view
     * @return
     */
    public static Bitmap getBitmapFromView(View view) {
        view.setDrawingCacheEnabled(true);
        view.buildDrawingCache(true);
        final Bitmap drawingCache = view.getDrawingCache();
        Bitmap bitmap;
        if (drawingCache != null) {
            bitmap = Bitmap.createBitmap(drawingCache);
            view.setDrawingCacheEnabled(false);
        } else {
            bitmap = null;
        }
        return bitmap;
    }

    public static Bitmap getBlurBmp(Context context, Bitmap srcBmp, float scale) {
        try {
            Bitmap dstBmp = Bitmap.createScaledBitmap(srcBmp, (int) (srcBmp.getWidth() * scale), (int) (srcBmp.getHeight() * scale), false);

            Class<?> cScreenShotUtils = Class.forName("miui.util.ScreenshotUtils");
            Method mGetBlurBackground = cScreenShotUtils.getMethod("getBlurBackground", Bitmap.class, Bitmap.class);
            Bitmap bluredBmp = (Bitmap) mGetBlurBackground.invoke(cScreenShotUtils, dstBmp, null);
//            srcBmp.recycle();
            dstBmp.recycle();
            return bluredBmp;
        } catch (Exception e) {
        }

        return null;
    }

    /**
     * 图片二值化代码
     * 其中的2最小可以设置为1，数值越小，二值化程度越高，速度越慢；反之。
     *
     * @return
     */
    public static Bitmap gray2Binary(Bitmap graymap) {
        //得到图形的宽度和长度
        int width = graymap.getWidth();
        int height = graymap.getHeight();
        //创建二值化图像
        Bitmap binarymap = null;
        binarymap = graymap.copy(Bitmap.Config.ARGB_8888, true);
        //依次循环，对图像的像素进行处理
        for (int i = 0; i < width; i += 1) {
            for (int j = 0; j < height; j += 2) {
                //得到当前像素的值
                int col = binarymap.getPixel(i, j);
                //得到alpha通道的值
                int alpha = col & 0xFF000000;
                //得到图像的像素RGB的值
                int red = (col & 0x00FF0000) >> 16;
                int green = (col & 0x0000FF00) >> 8;
                int blue = (col & 0x000000FF);
                // 用公式X = 0.3×R+0.59×G+0.11×B计算出X代替原来的RGB
                int gray = (int) ((float) red * 0.3 + (float) green * 0.59 + (float) blue * 0.11);
                //对图像进行二值化处理
                if (gray <= 95) {
                    gray = 0;
                } else {
                    gray = 255;
                }
                // 新的ARGB
                int newColor = alpha | (gray << 16) | (gray << 8) | gray;
                //设置新图像的当前像素值
                binarymap.setPixel(i, j, newColor);
            }
        }
        return binarymap;
    }

    /**
     * 适配安卓10的保存文件
     *
     * @param context 上下文
     * @param bitmap  图片
     */
    @RequiresApi(api = Build.VERSION_CODES.Q)
    public static String saveBitmapOfQ(Context context, Bitmap bitmap) {

        String fileName = "image" + RandomAllUtil.getNum(556564564, 595615615) + ".png";
        ContentValues values = new ContentValues();
        values.put(MediaStore.Images.Media.DESCRIPTION, "图片a");
        values.put(MediaStore.Images.Media.DISPLAY_NAME, fileName);   // 文件名
        values.put(MediaStore.Images.Media.MIME_TYPE, "image/png");
        values.put(MediaStore.Images.Media.TITLE, fileName);
        values.put(MediaStore.Images.Media.RELATIVE_PATH, "Pictures");

        Uri external = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
        ContentResolver resolver = context.getContentResolver();

        Uri insertUri = resolver.insert(external, values);
        OutputStream os = null;
        if (insertUri != null) {
            try {
                os = resolver.openOutputStream(insertUri);
                bitmap.compress(Bitmap.CompressFormat.PNG, 80, os);
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                try {
                    if (os != null) {
                        os.close();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return fileName;
    }

    public static Bitmap getLockscreenBmp(Context context) {
        try {
            Class<?> cThemeResources = Class.forName("miui.content.res.ThemeResources");
            Method mGetLockWallpaperCache = null;
            mGetLockWallpaperCache = cThemeResources.getDeclaredMethod("getLockWallpaperCache", Context.class);
            BitmapDrawable backgound = (BitmapDrawable) mGetLockWallpaperCache.invoke(cThemeResources, context);
            Bitmap srcBmp = backgound.getBitmap();
            return srcBmp;
        } catch (Exception e) {
        }
        return null;
    }

    public static void setTransparentStatusBar(Window targetWindow) {
        if (Build.VERSION.SDK_INT < 19) {
            return;
        }

        try {
            Class<? extends Window> clazz = targetWindow.getClass();
            int tranceFlag = 0;
            int darkModeFlag = 0;
            Class<?> layoutParams = Class
                    .forName("android.view.MiuiWindowManager$LayoutParams");

            Field field = layoutParams
                    .getField("EXTRA_FLAG_STATUS_BAR_TRANSPARENT");
            tranceFlag = field.getInt(layoutParams);

            field = layoutParams.getField("EXTRA_FLAG_STATUS_BAR_DARK_MODE");
            darkModeFlag = field.getInt(layoutParams);

            Method extraFlagField = clazz.getMethod("setExtraFlags", int.class,
                    int.class);
            // 状态栏透明
//            extraFlagField.invoke(targetWindow, tranceFlag, tranceFlag);
            // //状态栏darkMode
            // extraFlagField.invoke(window, darkModeFlag, darkModeFlag);
            // 即透明又darkMode
            extraFlagField.invoke(targetWindow, tranceFlag, tranceFlag |
                    darkModeFlag);

            targetWindow.addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
        } catch (Exception e) {
        }
    }

    public static int getTextWidth(Paint paint, String str) {
        int iRet = 0;
        if (str != null && str.length() > 0) {
            int len = str.length();
            float[] widths = new float[len];
            paint.getTextWidths(str, widths);
            for (int j = 0; j < len; j++) {
                iRet += (int) Math.ceil(widths[j]);
            }
        }
        return iRet;
    }

    public static void showDialog(Context context, String dialogTitle, @NonNull DialogInterface.OnClickListener onClickListener) {
        AlertDialog.Builder builder = new AlertDialog.Builder(context);
        builder.setMessage(dialogTitle);
        builder.setPositiveButton("确定", onClickListener);
        builder.setNegativeButton("取消", null);
        builder.create().show();
    }

}
